package com.xlp.snake.controller;

import java.awt.Component;
import java.awt.Point;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.lang.reflect.Executable;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

import javax.swing.JOptionPane;

import org.omg.CORBA.SystemException;

import com.xlp.snake.entities.Food;
import com.xlp.snake.entities.Ground;
import com.xlp.snake.entities.Snake;
import com.xlp.snake.listener.SnakeListener;
import com.xlp.snake.util.Global;
import com.xlp.snake.view.GamePanel;

public class Controller extends KeyAdapter implements SnakeListener {
	private Snake snake;
	private Food food;
	private Ground ground;
	private GamePanel gamePanel;
	//public static int a = 2;


	// 创建构造方法，用于赋值
	public Controller(Snake snake, Food food, Ground ground, GamePanel gamePanel) {
		super();
		this.snake = snake;
		this.food = food;
		this.ground = ground;
		this.gamePanel = gamePanel;
	}

	@Override
	public void keyPressed(KeyEvent e) {
		// 根据按键改变蛇的方向
		switch (e.getKeyCode()) { // 获取用户按的键
		case KeyEvent.VK_UP:
			snake.changeDirection(Snake.UP);
			break;
		case KeyEvent.VK_DOWN:
			snake.changeDirection(Snake.DOWN);
			break;
		case KeyEvent.VK_LEFT:
			snake.changeDirection(Snake.LEFT);
			break;
		case KeyEvent.VK_RIGHT:
			snake.changeDirection(Snake.RIGHT);
			break;
		case KeyEvent.VK_ENTER:
			Snake.life = true;
			newGame();
			snake.zanting();
			break;
		case KeyEvent.VK_SPACE:
			Snake.pause = !Snake.pause; 
			/*a++;
			if (a % 2 == 0) {
				Snake.life = true;
				//newGame();
				a=2;
			} else if (a % 2 != 0) {
				Snake.life = false;
			}*/
			break;
		case KeyEvent.VK_W:
			Snake.jiasu();
			break;
		case KeyEvent.VK_S:
			Snake.jiansu();
			break;
		}
			
	}


	@Override
	public void snakeMoved(Snake snake) {
		// 判断蛇是否吃到食物
		if (food.isSnakeEatFood(snake)) {
			snake.eatFood(); // 蛇吃掉食物 ，变长
			food.newFood(ground.getPoint()); // 吃到食物后再随机产生食物
		}

		// 判断蛇是否碰到石头
		if (ground.isSnakeEatRock(snake)) {
			snake.die();
			
		}

		// 判断是否吃到身体
		if (snake.isEatBody()) {
			snake.die();
		}

		// 显示的组件重新显示
		gamePanel.display(snake, food, ground);
	}


	// 开始新游戏
	public void newGame() {
		snake.start();
		food.newFood(ground.getPoint());
	}
}
